package com.woniu.common.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.druid.util.StringUtils;
import com.woniu.common.constans.Constants;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;

public class TokenUtil {
    public static <T> T getObj(HttpServletRequest request, Class<T> clazz) {
        String token = request.getHeader(Constants.TOKEN);
        if (StringUtils.isEmpty(token) || "".equals(token) || token == null) return null;
        //解析token
        JWT jwt = JWTUtil.parseToken(token);
        try {
            T obj = clazz.newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                if (jwt.getPayload(field.getName()) != null) {
                    Object value = jwt.getPayload(field.getName());
                    if (value != null) {
                        if (field.getType() == Integer.class)
                            field.set(obj, new Integer(String.valueOf(value)));
                        else if (field.getType() == String.class)
                            field.set(obj, String.valueOf(value));
                    }
                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
